package com.sinaweibo.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.jishigou.core.IWeibo;
import com.jishigou.po.WeiboImagePO;
import com.jishigou.util.HttpUtil;
import com.jishigou.util.StringUtil;

public class Weibo{
	private static String loginUrl = "http://weibo.gb246.com/jishigou/index.php?mod=login&code=dologin";
	String hash = null;
	public boolean login(String nickName, String pwd) throws Exception{
		//client = new DefaultHttpClient();
		DefaultHttpClient client = new DefaultHttpClient();
		Map loginMap = new HashMap();
		if(hash==null){
			hash = getHash();
		}
		loginMap.put("password", pwd);
		loginMap.put("username", nickName);
		loginMap.put("FORMHASH", hash);
		NameValuePair[] data = HttpUtil.fillParam(loginMap);
		//InputStream is =  doPost(client, loginUrl, data, null);
		String res = HttpUtil.doPostString(loginUrl,data,null);
		//String res = readInputStream(is, charCode);
	//	System.out.println(res);
		boolean isLogin = false;
		if(res.indexOf("无法登录")!=-1){
			//System.out.println("登录失败");
			isLogin = false;
		}else{
			//System.out.println("登录成功");
			isLogin=true;
		}
		return isLogin;
	}
	
	/**
	 * 发网络图片直接发URL字符串
	 * @param msg
	 * @param imageId
	 * @throws Exception
	 */
	public void addWeibo(String msg,String imageId) throws Exception {
		Map map = new HashMap();
		map.put("imageid", imageId);
		map.put("content", msg);
		NameValuePair[] data = HttpUtil.fillParam(map);
		String res = HttpUtil.doPostString(
				"http://weibo.gb246.com/jishigou/ajax.php?mod=topic&code=do_add&act=reply",
				data, null);
		System.out.println("--" + res);
	}

	private String uploadUrl="http://weibo.gb246.com/jishigou/ajax.php?mod=uploadify&code=image&type=normal&iitem=&iitemid=0";
	public boolean addWeiboWithImages(String msg,String imgPath) throws Exception {
	//	File file = new File(
		
		Map<String,Object> data = new HashMap<String, Object>();
	//	data.put("cookie_auth", cookie_auth);
		//data.put("FORMHASH", cookie_auth);
		if(HttpUtil.getHttpStatus(imgPath)==404){
			log.error("image is 404 "+imgPath);
			return false;
		}
		if(!StringUtil.isNullOrBlank(imgPath)){
			if(imgPath.startsWith("http")){
				addWeibo(msg+" "+imgPath, null);
			}else{
				File file = new File(imgPath);
				data.put( "topic",file);
				WeiboImagePO po = HttpUtil.uploadFile(data,imgPath);
				if(po == null){
					log.error("image up load failed "+imgPath);
					return false;
				}
				addWeibo(msg,po.getImageId());
			}
			
		}
		
		return true;
	}
	
	private String delWeiboUrl = "http://weibo.gb246.com/jishigou/ajax.php?mod=topic&code=delete";
	public boolean delWeibo(String weiboId) throws Exception{
		Map<String, String> data = new HashMap<String, String>();
		data.put("tid", weiboId);
		String res = HttpUtil.doPostString(delWeiboUrl, HttpUtil.fillParam(data), null);
		return res.indexOf("删除微博")!=-1&&res.indexOf("金币")!=-1;
	}
	
	public String getHash() throws Exception {
		// TODO Auto-generated method stub
		String res = HttpUtil.doGetString("http://weibo.gb246.com/jishigou/index.php", null);
		Document content  = Jsoup.parse(res);
		Elements es = content.getElementsByAttributeValue("name", "FORMHASH");
		if(es == null || es.size()==0){
			throw new NullPointerException("no formhash element");
		}
		String formHash = null;
		for(Element e : es){
			formHash =  e.attr("value");
			if(!StringUtil.isNullOrBlank(formHash)){
				break;
			}
		}
		//String fromHash = e.attr("value");
		return formHash;
	}
	
	public String getCookieAuth() throws Exception{
		String cookieAuth = "";
		HttpGet get = new HttpGet("http://weibo.gb246.com/jishigou/index.php");
		InputStream is =  HttpUtil.getHttpClient().execute( get ).getEntity().getContent();
		BufferedReader in = new BufferedReader(
				new InputStreamReader(is, HttpUtil.charCode));
		String line;
		while ((line = in.readLine()) != null) {
			if(line.indexOf("cookie_auth")!=-1){
				line = StringUtil.getOneStringByRegex(line, "'cookie_auth': '(\\S+)'");
				//in.close();
				
				return line;
			}
		}
		return cookieAuth;
	}
	
	public static void main(String[] args) {
		HttpUtil.charCode = "utf-8";

		final Weibo cw = new Weibo();
		final String msg = "testWithImg";
		//String img = "E:/code.jpg";
		final String img = "http://image.market.gb246.com/tour/26b0bd94-a5ba-42c8-940c-10dd6056a934.jpg";
		try {
			cw.login("admin","goodbaby");
			//cw.addWeiboWithImages(msg,img);
			/*for(int i=0;i<28;i++){
			cw.delWeibo(i+"");
			}*/
			int msgSize = 7197;
			
			int end = 21622;//from+msgSize
			int from = 21609;//end-1000;
			int count=0;
			for(int i=from;i<end;i++){
				final int index = i;
				new Thread(){

					@Override
					public void run() {
						try {
							cw.delWeibo(index+"");
							//cw.addWeibo(msg+img, "");
							//cw.addWeiboWithImages(msg, img);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}.start();
				System.out.println("已经删除"+(count++)+" ID"+i);
			}
		/*	String cookie_auth = cw.getCookieAuth();
			if(org.jsoup.helper.StringUtil.isBlank(cookie_auth)){
				System.out.println("cookie auth is blank");
			}
			System.out.println(cookie_auth);*/
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main1(String[] args) {
		String con = "<script type='text/javascript'>			window.parent.imageUploadifyComplete('20', './images/topic/5/62/20_s.jpg', 'genimg.jpg');			window.parent.imageUploadifyAllComplete();			</script>";
		String regex = "window.parent.imageUploadifyComplete\\('([^']+)', '([^']+)', '([^']+)'\\);";
		int [] ind = {1,2,3};
		List<String> list = StringUtil.getStringsByRegex(regex, ind, con);
		System.out.println(list.get(1));
	}
	
	Logger log = Logger.getLogger(Weibo.class);
}
